package com.qf.mybatisDynamicSqlDemo.until;

import com.qf.mybatisDynamicSqlDemo.entity.Book;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 刘欣
 * @createTime 2022/12/22 21:13
 * @description
 */
public class FileReadWriteUntil {
    private static BufferedWriter writer;
    private static BufferedReader reader;
    private static String path = "src/main/resources/books.txt";

    static {

        try {

            writer = new BufferedWriter(new FileWriter(path, true));
            reader = new BufferedReader(new FileReader(path));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void write(List<Book> books) throws IOException {
        if (books != null || books.size() > 0) {
            for (Book book : books) {
                String cvs = book.bookToCvs();
                writer.write(cvs);
                writer.newLine();
                writer.flush();
            }

        }
    }

    public static List<Book> read(Integer num) {
        List<Book> books = new ArrayList<>();
        try {
            String str = "";
            while ((str = reader.readLine()) != null) {
                books.add(Book.cvsToBook(str));
                if (books.size() == num) {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception exception) {
            exception.printStackTrace();
        }
        return books;
    }


    public static void closeWrite() {
        try {
            if (writer != null) {
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void closeRead() {
        try {
            if (reader != null) {
                reader.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
